package com.insmess.speech.common.util;

import cn.hutool.json.JSONUtil;
import com.insmess.speech.common.constant.PathConstant;
import com.insmess.speech.dto.SpeechConfigDto;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 敏感词工具
 */
@Slf4j
public class SensitiveWordUtils {
    private static final List<String> SENSITIVE_WORD_LIST = new ArrayList<>();

    private static final String SENSITIVE_WORD_LIST_FILE;

    static {
        SENSITIVE_WORD_LIST_FILE = PathConstant.INSMESS_SPEECH_PATH + File.separator + "storage" + File.separator + "sensitive_word_list";
        File sensitiveWordFile = new File(SENSITIVE_WORD_LIST_FILE);
        if (!sensitiveWordFile.getParentFile().exists()) {
            sensitiveWordFile.getParentFile().mkdirs();
        }
        if (sensitiveWordFile.exists()) {
            log.info("敏感词文件已存在，读取文件敏感词：{}", SENSITIVE_WORD_LIST_FILE);
            readSensitiveWord();
        } else {
            //创建该文件
            try {
                sensitiveWordFile.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 添加敏感词
     * @return
     */
    public static void addSensitiveWord(String keyWord) {
        if (SENSITIVE_WORD_LIST.contains(keyWord)) {
            throw new RuntimeException("关键字已存在，添加失败：" + keyWord);
        }
        SENSITIVE_WORD_LIST.add(keyWord);
        //根据长度排序
        Collections.sort(SENSITIVE_WORD_LIST, (s1, s2) -> s2.length() - s1.length());
    }

    /**
     * 删除敏感词
     * @return
     */
    public static void removeSensitiveWord(String keyWord) {
        SENSITIVE_WORD_LIST.remove(keyWord);
        writeSensitiveWord();
    }

    /**
     * 获取敏感词列表
     * @return
     */
    public static List<String> getSensitiveWordList() {
        return SENSITIVE_WORD_LIST;
    }

    @SneakyThrows
    private static void readSensitiveWord() {
        List<String> list = FileUtils.readLines(new File(SENSITIVE_WORD_LIST_FILE), "utf-8");
        SENSITIVE_WORD_LIST.clear();
        SENSITIVE_WORD_LIST.addAll(list);
    }

    @SneakyThrows
    private static void writeSensitiveWord() {
        FileUtils.writeLines(new File(SENSITIVE_WORD_LIST_FILE), SENSITIVE_WORD_LIST);
    }
}
